package chaincode

import (
	"encoding/json"
	"fmt"
	"github.com/hyperledger/fabric-contract-api-go/contractapi"
)

// HouseContract 提供用于管理房屋资产的功能
type HouseContract struct {
	contractapi.Contract
}

// House 结构表示房屋信息
type House struct {
	ID            string `json:"id"`       //主键
	Owner         string `json:"owner"`    //主人
	HousePrice    string `json:"price"`    //房屋价格
	HouseArea     string `json:"area"`     //房屋面积
	HouseImages   string `json:"images"`   //房屋图片
	HouseVerified string `json:"verified"` //房屋状态验证
}

// InitLedger 函数用于初始化智能合约的分类帐，向其中添加一组基本的房屋信息。
func (s *HouseContract) InitLedger(ctx contractapi.TransactionContextInterface) error {
	// 创建一个包含两个房屋信息的切片，每个房屋信息都包括不同的属性。
	assets := []House{
		{"1", "张三", "2000000", "150", "1.jpg", "1"},
		{"2", "李四", "3000000", "200", "2.jpg", "1"},
	}
	// 遍历切片中的每个房屋信息并将其添加到分类帐中。
	for _, asset := range assets {
		assetJSON, err := json.Marshal(asset)
		if err != nil {
			return err
		}

		err = ctx.GetStub().PutState(asset.ID, assetJSON)
		if err != nil {
			return fmt.Errorf("无法将数据存储到区块链分类帐中： %v", err)
		}
	}
	return nil
}

// GetAllHouseAssets 获取整个房屋区块链的资源
func (s *HouseContract) GetAllHouse(ctx contractapi.TransactionContextInterface) ([]*House, error) {
	//对startKey和endKey进行空字符串范围查询
	// chaincode命名空间中所有资产的开放式查询。
	resultsIterator, err := ctx.GetStub().GetStateByRange("", "")
	if err != nil {
		return nil, err
	}
	defer resultsIterator.Close()

	var assets []*House
	for resultsIterator.HasNext() {
		queryResponse, err := resultsIterator.Next()
		if err != nil {
			return nil, err
		}

		var asset House
		err = json.Unmarshal(queryResponse.Value, &asset)
		if err != nil {
			return nil, err
		}
		assets = append(assets, &asset)
	}
	return assets, nil
}

// CreateHouseAsset 添加房屋资产
func (s *HouseContract) CreateHouse(ctx contractapi.TransactionContextInterface, id, owner, housePrice, houseArea, houseImages, houseVerified string) error {
	house := House{
		ID:            id,
		Owner:         owner,
		HousePrice:    housePrice,
		HouseArea:     houseArea,
		HouseImages:   houseImages,
		HouseVerified: houseVerified,
	}
	houseJSON, err := json.Marshal(house)
	if err != nil {
		return err
	}
	return ctx.GetStub().PutState(id, houseJSON)
}

// 批量添加

// ReadHouseAsset 函数返回存储在世界状态中的具有给定ID的资产。
func (s *HouseContract) ReadHouseAsset(ctx contractapi.TransactionContextInterface, id string) (*House, error) {
	assetJSON, err := ctx.GetStub().GetState(id)
	if err != nil {
		return nil, fmt.Errorf("无法从中心读取数据：%v", err)
	}

	if assetJSON == nil {
		return nil, fmt.Errorf("资产 %s 不存在", id)
	}
	var asset House
	err = json.Unmarshal(assetJSON, &asset)
	if err != nil {
		return nil, err
	}
	return &asset, nil
}

// UpdateHouseAsset 更改房屋资产
func (s *HouseContract) UpdateHouseAsset(ctx contractapi.TransactionContextInterface, id, owner, housePrice, houseArea, houseImages, houseVerified string) error {
	exists, err := s.HouseExists(ctx, id)
	if err != nil {
		return err
	}
	if !exists {
		return fmt.Errorf("资产 %s 不存在", id)
	}

	// overwriting original asset with new asset
	asset := House{
		ID:            id,
		Owner:         owner,
		HousePrice:    housePrice,
		HouseArea:     houseArea,
		HouseImages:   houseImages,
		HouseVerified: houseVerified,
	}
	assetJSON, err := json.Marshal(asset)
	if err != nil {
		return err
	}

	return ctx.GetStub().PutState(id, assetJSON)
}

// DeleteHouseAsset 删除房屋资源
func (s *HouseContract) DeleteHouseAsset(ctx contractapi.TransactionContextInterface, id string) error {
	exists, err := s.HouseExists(ctx, id)
	if err != nil {
		return err
	}
	if !exists {
		return fmt.Errorf("资产 %s 不存在", id)
	}

	return ctx.GetStub().DelState(id)
}

// HouseExists 函数在区块链的世界状态中检查给定ID的房屋是否存在。
func (s *HouseContract) HouseExists(ctx contractapi.TransactionContextInterface, id string) (bool, error) {
	assetJSON, err := ctx.GetStub().GetState(id)
	if err != nil {
		return false, fmt.Errorf("无法从中心读取数据：%v", err)
	}
	return assetJSON != nil, nil
}

// TransferHouseAsset 更新区块链中具有给定ID的资产的所有者字段，并返回之前的所有者。
func (s *HouseContract) TransferHouseAsset(ctx contractapi.TransactionContextInterface, id string, newOwner string) (string, error) {
	asset, err := s.ReadHouseAsset(ctx, id)
	if err != nil {
		return "", err
	}

	oldOwner := asset.Owner
	asset.Owner = newOwner

	assetJSON, err := json.Marshal(asset)
	if err != nil {
		return "", err
	}

	err = ctx.GetStub().PutState(id, assetJSON)
	if err != nil {
		return "", err
	}
	return oldOwner, nil
}
